import React from 'react';
import { Button, Col, Divider, Form, Input, message, Modal, Row, Select, Table, Icon, Pagination } from 'antd';
import { getAnswerList, answerDelete } from '@/services/knowledgemanagement';
import AddOrEditAnswer from '@/pages/KnowledgeManagement/AnswerLibrary/rightList/addOrEditAnswer';
import ReferenceCase from '@/pages/KnowledgeManagement/AnswerLibrary/rightList/referenceCaseModal';
import pen from '@/assets/knowledge/pen.png';
import deleteZdy from '@/assets/knowledge/delete.png';
import referImg from '@/assets/knowledge/refer.svg';

class RightList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentNode: {
        disabled: false,
        id: '',
        name: '',
        parentId: '',
        parentPath: '',
        weight: 0
      },
      query: {
        current: 1,
        size: 10,
        search: '',
        type: 0
      },
      loading: true,
      total: 0,
      records: [],
      modalType: 'add',
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    };
    this.getList();
  }

  /**
   * 接收从左侧树传来的currentNode
   * @returns {*}
   */
  receiveNode = currentNode => {
    this.setState({ currentNode }, () => {
      this.getList();
    })
  }

  /**
   * 获取列表数据
   */
  getList = () => {
    this.setState({ loading: true }, async () => {
      let { query, currentNode } = this.state;
      query.categoryId = currentNode.id;
      query.categoryParentPath = currentNode.parentPath;
      const res = await getAnswerList(query);
      let totalPage = Math.ceil(res.total / query.size);
      if (!res.records.length && res.total > 0) {
        query.current = query.current - 1;
        this.setState({ ...query }, () => {
          this.getList();
        });
      };
      this.setState({
        loading: false,
        records: res.records ? res.records : [],
        total: res.total
      })
    })
  }

  /**
   * 根据搜索条件查询
   * @returns {*}
   */
  queryByCondition = () => {
    const formData = this.props.form.getFieldsValue();
    let { query } = this.state;
    query.search = formData.search;
    query.type = formData.type;
    query.current = 1;
    this.setState({ query }, () => {
      this.getList();
    })
  }

  /**
   * 根据分页查询
   * @returns {*}
   */
  queryByPage = (current, size) => {
    let { query } = this.state;
    query.current = current;
    query.size = size;
    this.setState({ query }, () => {
      this.getList();
    })
  }

  /**
   * 删除答案
   * @returns {*}
   */
  deleteAnswer = (data) => {
    Modal.confirm({
      title: data.isUsing ? '该答案正在被知识点引用，删除后这些知识点的答案将变为空，是否确定删除？' : '是否确认删除此答案？',
      okType: 'danger',
      okText: '删除',
      cancelText: '取消',
      onOk: async () => {
        const res = await answerDelete({ id: data.id })
        message.info(res.message);
        this.getList();
      }
    })
  }

  /**
   * 打开 新增/编辑 答案的弹窗
   * @returns {*}
   */
  openAddOrEditAnswer = (modalType, row) => {
    this.setState({ modalType }, () => {
      const { currentNode } = this.state
      this.AddOrEditAnswer.initModal(modalType, row, currentNode);
    })
  }

  /**
   * 打开引用情况弹窗
   * @returns {*}
   */
  openReferenceCase = (row) => {
    if (this.ReferenceCase) {
      this.ReferenceCase.info(row.id);
    };
  }

  render() {
    const { currentNode, loading, total, query, records, modalType } = this.state;
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: '标题',
        dataIndex: 'question',
        width: '60%',
        onHeaderCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '操作',
        width: '40%',
        align: 'center',
        // onHeaderCell: () => ({style:{fontWeight: 600, fontSize: '16px'}}),
        render: (text, row) => {
          return (
            <div>
              <Button type={'primary'} size={'small'} onClick={() => this.openAddOrEditAnswer('edit', row)}>
                <span style={{ verticalAlign: 'middle' }}>编辑</span>
              </Button>
              <Button type={'danger'} size={'small'} style={{ margin: '0 5px' }} onClick={() => this.deleteAnswer(row)}>
                <span style={{ verticalAlign: 'middle' }}>删除</span>
              </Button>
              <Button size={'small'} style={{ background: '#09B2FF', color: '#ffffff', border: 0 }} onClick={() => this.openReferenceCase(row)}>
                <img src={referImg} style={{ verticalAlign: 'middle', marginRight: 5 }} />
                <span style={{ verticalAlign: 'middle' }}>引用情况</span>
              </Button>
            </div>
          )
        }
      }
    ];

    return (
      <div>
        <Row style={{ marginTop: 10 }}>
          <Col span={20}>
            <Form layout={'inline'}>
              <Form.Item>
                {getFieldDecorator('search')(
                  <Input.Search placeholder={'请输入关键词'} onSearch={this.queryByCondition} style={{ width: 350 }} />
                )}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('type', { initialValue: 0 })(
                  <Select style={{ width: 160 }} suffixIcon={<Icon type="caret-down" />}>
                    <Select.Option value={0}>搜索问题</Select.Option>
                    <Select.Option value={1}>搜索答案</Select.Option>
                  </Select>
                )}
              </Form.Item>
              <Form.Item>
                <Button type={'primary'} onClick={this.queryByCondition}>查询</Button>
              </Form.Item>
            </Form>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            <Button type={'primary'} disabled={currentNode.parentId === '0'} onClick={() => this.openAddOrEditAnswer('add')}>新增</Button>
          </Col>
        </Row>
        <Row style={{ marginTop: 24 }}>
          <Col>
            <Table
              rowKey={'id'}
              // onHeaderRow={() => ({style:{textAlign: 'center'}})}
              dataSource={records}
              loading={loading}
              columns={columns}
              pagination={false}
              scroll={{ y: 587 }}
            />
            {total > 10 ? (
              <Pagination
                style={{ textAlign: 'right', marginTop: 16 }}
                total={total}
                current={query.current}
                // showSizeChanger={true}
                showQuickJumper={true}
                // onShowSizeChange={this.queryByPage}
                onChange={this.queryByPage}
              />
            ) : null}
          </Col>
        </Row>
        <AddOrEditAnswer
          onRef={ref => this.AddOrEditAnswer = ref}
          modalType={modalType}
          getList={this.queryByCondition}
        />
        <ReferenceCase onRef={ref => this.ReferenceCase = ref} />
      </div>
    );
  }
}

export default Form.create()(RightList);
